<template>

	<view class="">
		<view class="avatar-section">
			<avater-upload ref="avatarRef" v-model="avatarUrl" :size="220" shape="circle" borderColor="#409eff"
				borderWidth="3" uploadText="暂无头像" action="https://dn.xinnuanyun.com/suittc_dn/wechat/uploadAvatar"
				:headers="{ Authorization: 'Bearer ' + token }" name="avatar" @success="handleSuccess"
				@error="handleError" :on-save-avatar="handleSaveAvatar"></avater-upload>
		</view>

		<view class="button-group">
			<button class="button" @click="handleChooseImage" :disabled="!isComponentReady">
				<uni-icons type="image" size="24" color="#fff" class="button-icon"></uni-icons>
				相册选择
			</button>
			<button class="button" @click="handleTakePhoto" :disabled="!isComponentReady">
				<uni-icons type="camera" size="24" color="#fff" class="button-icon"></uni-icons>
				拍照上传
			</button>
			<!-- <view class="action-btns" v-if="showPreview">
				<button class="button button--save" @click="handleSaveAvatar" :disabled="!isComponentReady">
					保存头像
				</button>
				<button class="button button--danger" @click="handleClearAvatar" :disabled="!isComponentReady">
					清除头像
				</button>
			</view> -->
		</view>

		<!-- 预览区域 -->
		<!-- <view class="preview-section" v-if="showPreview">
			<view class="preview-title">预览:</view>
			<view class="preview-image-container">
				<image :src="avatarUrl" class="preview-image" mode="widthFix"></image>
			</view>
		</view> -->
	</view>

</template>

<script setup>
	import {
		ref,
		onMounted,
		computed
	} from 'vue';
	import AvaterUpload from '@/components/avater-upload/avater-upload.vue';
	import {
		useUserStore
	} from "@/store/user";
	import {
		onLoad
	} from "@dcloudio/uni-app";
	// 获取store实例
	const userStore = useUserStore();
	// 头像URL
	const avatarUrl = ref('');
	// 头像组件引用
	const avatarRef = ref(null);

	// 加载状态
	const isLoading = ref(false);
	// 模拟token
	const token = ref('');
	const showPreview = ref(false)

	onLoad(() => {
		avatarUrl.value = userStore.getUserInfo().avatar
	})

	// 计算属性：组件是否准备就绪
	const isComponentReady = computed(() => {
		return avatarRef.value !== null;
	});

	// 显示提示消息
	const showToast = (message) => {
		uni.showToast({
			title: message,
			icon: 'none',
			duration: 3000
		});
	};

	// 从相册选择图片
	const handleChooseImage = () => {
		if (!isComponentReady.value) {
			showToast('组件尚未准备就绪，请稍候再试');
			return;
		}

		try {
			const success = avatarRef.value.chooseImage();
			if (!success) {
				showToast('操作失败，请稍候再试');
			}
		} catch (error) {
			showToast('操作失败: ' + (error.message || '未知错误'));
			console.error('选择图片失败:', error);
		}
	};

	// 拍照上传
	const handleTakePhoto = () => {
		if (!isComponentReady.value) {
			showToast('组件尚未准备就绪，请稍候再试');
			return;
		}

		try {
			const success = avatarRef.value.takePhoto();
			if (!success) {
				showToast('操作失败，请稍候再试');
			}
		} catch (error) {
			showToast('操作失败: ' + (error.message || '未知错误'));
			console.error('拍照失败:', error);
		}
	};

	// 清除头像
	const handleClearAvatar = () => {
		avatarUrl.value = '';
		showToast('头像已清除');
		showPreview.value = false
	};

	// 上传成功回调
	const handleSuccess = (result) => {
		uni.showLoading()
		showPreview.value = true
		// 如果是服务器返回的结果，假设包含了远程URL
		if (result.body.url) {
			avatarUrl.value = result.body.url;
			userStore.setUserAvatar(avatarUrl.value)
			uni.hideLoading()
			uni.showToast({
				title: "更新头像成功",
				icon: 'success'
			})
		} else {
			uni.hideLoading()
			uni.showToast({
				title: "上传头像失败",
				icon: 'fail'
			})
		}
	};
	const handleSaveAvatar = () => {
		uni.$emit('saveAvatarClicked');
	}

	// 上传失败回调
	const handleError = (error) => {
		console.error('上传失败:', error);

		let errorMessage = '操作失败';
		if (error.errMsg) {
			if (error.errMsg.includes('cancel')) {
				errorMessage = '操作已取消';
			} else if (error.errMsg.includes('deny')) {
				errorMessage = '没有权限，请在设置中开启权限';
			} else {
				errorMessage = error.errMsg;
			}
		}

		showToast(errorMessage);
	};
</script>

<style scoped lang="scss">
	.avater-container {
		width: 100vw;
		height: 100vw;

		.avater-container-detail {
			width: 85vw;
			height: 85vw;
			background-color: #f1f1f1;
			margin: 7vw auto;
			border-radius: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}



	.avatar-section {
		margin: 60rpx 0;
	}

	.button-group {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
		width: 80%;
		position: absolute;
		bottom: 250rpx;
		left: 50%;
		transform: translateX(-50%);

	}

	.button {
		height: 90rpx;
		line-height: 90rpx;
		text-align: center;
		background-color: #409eff;
		color: white;
		border-radius: 45rpx;
		font-size: 32rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 500rpx;
	}

	.action-btns {
		width: 500rpx;
		display: flex;
		margin: 0 auto;
	}

	.button--danger {
		background-color: #f56c6c;
		width: 230rpx;
		margin-left: 40rpx;
	}

	.button--save {
		background: #333;
		width: 230rpx;
	}

	.button-icon {
		margin-right: 15rpx;
	}

	.button:disabled {
		background-color: #c0c4cc;
		color: #fff;
		opacity: 0.7;
	}

	.preview-section {
		margin-top: 60rpx;
		padding: 20rpx;
		width: 80%;
		max-width: 500rpx;
		border-radius: 10rpx;
		background-color: white;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.preview-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
		text-align: center;
	}

	.preview-image-container {
		display: flex;
		justify-content: center;
	}

	.preview-image {
		width: 200rpx;
		height: 200rpx;
		border-radius: 10rpx;
		border: 1px solid #eee;
	}

	.loading-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.3);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 9999;
	}

	.loading-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: white;
		padding: 40rpx;
		border-radius: 10rpx;
	}

	.loading-text {
		margin-top: 20rpx;
		font-size: 28rpx;
		color: #333;
	}
</style>